import React, { ReactNode, useState, useEffect } from 'react'
import { Row, Col, Form, Button, Space, Divider } from 'antd'
import {
  SearchOutlined,
  ReloadOutlined,
  UpOutlined,
  DownOutlined,
} from '@ant-design/icons'
import './style.css'

// 过滤器项类型定义
export type FilterItemType =
  | 'input'
  | 'select'
  | 'date'
  | 'dateRange'
  | 'custom'

// 过滤器项配置接口
export interface FilterItemConfig {
  key: string
  label: string
  type: FilterItemType
  placeholder?: string
  options?: { label: string; value: string | number }[]
  defaultValue?: string | number | string[] | number[]
  required?: boolean
  rules?: Array<Record<string, unknown>>
  component?: ReactNode // 自定义组件
  span?: number // 自定义宽度，默认为8（PC端一行3个）
  props?: Record<string, unknown> // 传递给组件的其他属性
}

// 组件属性接口
export interface TableFilterProps {
  filters: FilterItemConfig[]
  onSearch?: (values: Record<string, unknown>) => void
  onReset?: () => void
  initialValues?: Record<string, unknown>
  loading?: boolean
  showDivider?: boolean
  extraButtons?: ReactNode
  defaultCollapsed?: boolean // 默认是否折叠
}

// 响应式布局配置
const getResponsiveProps = () => {
  // 判断是否为移动设备
  const isMobile = window.innerWidth < 768
  return {
    itemSpan: isMobile ? 24 : 8, // 移动端一行1个，PC端一行3个
    buttonSpan: isMobile ? 24 : 8,
    formLayout: isMobile ? 'inline' : 'horizontal',
  }
}

const TableFilter: React.FC<TableFilterProps> = ({
  filters,
  onSearch,
  onReset,
  initialValues = {},
  loading = false,
  showDivider = true,
  extraButtons,
  defaultCollapsed = false,
}) => {
  const [form] = Form.useForm()
  const [responsive, setResponsive] = useState(getResponsiveProps())
  const [collapsed, setCollapsed] = useState(defaultCollapsed)

  // 监听窗口大小变化，更新响应式布局
  useEffect(() => {
    const handleResize = () => {
      setResponsive(getResponsiveProps())
    }

    window.addEventListener('resize', handleResize)
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [])

  // 处理搜索
  const handleSearch = () => {
    const values = form.getFieldsValue()
    onSearch?.(values)
  }

  // 处理重置
  const handleReset = () => {
    form.resetFields()
    onReset?.()
  }

  // 切换折叠状态
  const toggleCollapse = () => {
    setCollapsed(!collapsed)
  }

  return (
    <div className="table-filter-container">
      <Form
        form={form}
        layout={'horizontal'}
        initialValues={initialValues}
        onFinish={handleSearch}
        labelAlign="left"
      >
        <div className={`filter-content ${collapsed ? 'collapsed' : ''}`}>
          <Row gutter={[16, 16]} className="filter-row !gap-0">
            {filters.map((filter) => (
              <Col
                key={filter.key}
                xs={24}
                sm={filter.span || responsive.itemSpan}
                className={collapsed ? 'filter-item-collapsed' : ''}
              >
                <Form.Item
                  name={filter.key}
                  label={filter.label}
                  rules={filter.rules}
                  required={filter.required}
                >
                  {filter.component}
                </Form.Item>
              </Col>
            ))}
          </Row>
        </div>

        <Row className="filter-actions-row">
          <Col className="action-buttons-wrapper">
            <Space size={8} wrap>
              {filters.length > 3 && (
                <Button
                  type="text"
                  onClick={toggleCollapse}
                  icon={collapsed ? <DownOutlined /> : <UpOutlined />}
                  className="collapse-button"
                >
                  {collapsed ? '展开' : '收起'}
                </Button>
              )}
              <Button
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
                loading={loading}
              >
                搜索
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={handleReset}
                disabled={loading}
              >
                重置
              </Button>
              {extraButtons}
            </Space>
          </Col>
        </Row>
      </Form>
      {showDivider && <Divider style={{ margin: '16px 0' }} />}
    </div>
  )
}

export default TableFilter
